package com.hjw.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.hjw.entity.PasswordEncoder;
import com.hjw.entity.User;
import com.hjw.service.UserService;
import com.hjw.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/log")
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private RedisTemplate<String, User> redisTemplate;

    @PostMapping("/in") // /api/log/in
    public SaResult login(@RequestParam String username, @RequestParam String password) {
        log.info("用户名：{}", username);
        log.info("密码：{}", password);
        User user = userService.findByAccount(username);
        if (user == null) {
            return SaResult.get(200, "用户不存在", null);
        }
        if (user.getClosed() == 1) {
            return SaResult.get(203, "账号已被封禁", null);
        }
        boolean matches = passwordEncoder.matches(password, user.getPassword());

        if (!matches){
            return SaResult.get(203, "密码错误", null);
        }
        redisTemplate.opsForValue().set("user:" + user.getId(), user, 30, TimeUnit.MINUTES);
        StpUtil.login(user.getId());
        String token = StpUtil.getTokenValue();
        log.info("token={}", token);
        log.info("权限列表：{}", StpUtil.getPermissionList());
        log.info("角色列表：{}", StpUtil.getRoleList());
        Map<String, Object> map = new HashMap<>(2);
        map.put("token", token);
        return SaResult.get(200, "登录成功", map);
    }

    @GetMapping("/out")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.get(200, "退出成功", null);
    }

}